#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/ioctl.h>
#include "pwm_music.h"

#include "driver/fs4412_pwm.h"
#include "driver/fs4412_led.h"

void main()
{
	int fd, fd1, dev_fd, div, data, j, n, i;

	fd = open("/dev/adc", O_RDWR);//打开通过mknod命令创建的设备文件
	if (fd < 0) {
		perror("open");
		exit(1);
	}

    fd1 = open("/dev/led", O_RDWR);
	if (fd1 < 0) {
		perror("open");
		exit(1);
	}
    
    dev_fd = open("/dev/pwm",O_RDWR | O_NONBLOCK);
	if ( dev_fd == -1 ) {
		perror("open");
		exit(1);
	}

	while(1) {
		//应用程序通过read函数访问驱动的read接口，读取ad转换后的值
		//函数原型int read(int handle, void *buf, int count);
		//data用于存放转换后的数据
        read(fd,&data,sizeof (data));
        n = 1;
        if (data >= 500 && data < 1000) {
            ioctl(fd1,LED_ON,&n);
            for (i = 2; i <= 6; ++i) {
                ioctl(fd1, LED_OFF, &i);
            }
        } else if (data >= 1000 && data < 1500) {
            ioctl(fd1,LED_ON,&n);
            ++n;
            ioctl(fd1,LED_ON,&n);
            for (i = 3; i <= 6; ++i) {
                ioctl(fd1, LED_OFF, &i);
            }
        } else if (data >= 1500 && data < 2000) {
            ioctl(fd1,LED_ON,&n);
            ++n;
            ioctl(fd1,LED_ON,&n);
            ++n;
            ioctl(fd1,LED_ON,&n);
            for (i = 4; i <= 6; ++i) {
                ioctl(fd, LED_OFF, &i);
            }
        } else if (data >= 2000) {
                ioctl(dev_fd, PWM_ON);
                for(j = 0; j < sizeof(MotherLoveMeOnceAgain) / sizeof(Note); j++) {
                    div = (PCLK/256/4)/(MotherLoveMeOnceAgain[j].pitch);
                    ioctl(dev_fd, SET_CNT, &div);
                    usleep(MotherLoveMeOnceAgain[j].dimation * 100);
                    if (j % 2 == 0) {
                        //六个个灯亮的代码
                        for (i = 1; i <= 6; ++i) {
                            ioctl(fd1, LED_ON, &i);
                        }
                    } else {
                        //六个灯灭的代码
                        for (i = 1; i <= 6; ++i) {
                            ioctl(fd1, LED_OFF, &i);
                        }
                    }
                    read(fd,&data,sizeof (data));
                    if (data < 2000) {
                        ioctl(dev_fd, PWM_OFF);
                        break;
                    }
                }
        }
		sleep(1);//每隔一秒打印一次
	}
}